<template>
  <div class="message-board-page">
    <Header />
    <div class="page-header">
      <h2>心理问答</h2>
      <p class="subtitle">在这里提出您的心理困扰，专业医生为您解答</p>
    </div>
    
    <!-- 提问按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="showMessageBoardDialog">
        <el-icon><Plus /></el-icon>
        我要提问
      </el-button>
    </div>

    <!-- 问题列表 -->
    <div class="message-board-list" v-loading="loading">
      <div class="card-container">
        <el-card v-for="messageBoard in messageBoards" 
          :key="messageBoard.issueId" 
          class="message-board-card"
        >
          <div class="card-main">
            <div class="message-board-content">
              <div class="content-text">
                {{ messageBoard.text }}
              </div>
            </div>
            
            <div class="message-board-footer">
              <div class="message-board-meta">
                <span class="author">{{ messageBoard.createrName }}</span>
                <span class="time">{{ messageBoard.createTime }}</span>
              </div>
              <el-button 
                type="primary" 
                link
                @click="viewDetail(messageBoard.issueId)"
              >
                查看详情
                <el-icon class="el-icon--right"><ArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 提问对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="发布提问"
      width="50%"
    >
      <el-form :model="messageBoardForm" ref="messageBoardFormRef" :rules="rules">
        <el-form-item label="问题内容" prop="text">
          <el-input
            v-model="messageBoardForm.text"
            type="textarea"
            :rows="6"
            placeholder="请详细描述您的问题"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMessageBoard">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, ArrowRight } from '@element-plus/icons-vue'
import Header from '../../components/header.vue'
import Footer from '../../components/footer.vue'
import { getMessageBoardList, createMessageBoard, type MessageBoard } from '../../api/messageboard'

const router = useRouter()
const loading = ref(false)
const messageBoards = ref<MessageBoard[]>([])
const dialogVisible = ref(false)
const messageBoardFormRef = ref()

const messageBoardForm = ref({
  text: ''
})

const rules = {
  text: [
    { required: true, message: '请输入问题内容', trigger: 'blur' },
    { min: 10, max: 500, message: '内容长度应在10-500个字符之间', trigger: 'blur' }
  ]
}

// 获取问题列表
const fetchMessageBoards = async () => {
  loading.value = true
  try {
    const res = await getMessageBoardList()
    if (res.code === '200') {
      messageBoards.value = res.data
    }
  } catch (error) {
    console.error('获取问题列表失败:', error)
    ElMessage.error('获取问题列表失败')
  } finally {
    loading.value = false
  }
}

// 显示提问对话框
const showMessageBoardDialog = () => {
  const userRole = localStorage.getItem('userRole')
  if (!userRole) {
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', router.currentRoute.value.fullPath)
    ElMessage.warning('请先登录后再提问')
    router.push('/login')
    return
  }
  dialogVisible.value = true
}

// 提交问题
const submitMessageBoard = async () => {
  const userRole = localStorage.getItem('userRole')
  const userId = localStorage.getItem('userid')
  const doctorId = localStorage.getItem('doctorid')
  if (!userRole) {
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', router.currentRoute.value.fullPath)
    ElMessage.warning('请先登录后再提问')
    router.push('/login')
    return
  }

  if (!messageBoardFormRef.value) return
  
  await messageBoardFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await createMessageBoard({
          creatorId: userRole === 'doctor' ? Number(doctorId) : Number(userId),
          text: messageBoardForm.value.text,
        })
        if (res.code === '200') {
          ElMessage.success('提问成功')
          dialogVisible.value = false
          messageBoardForm.value.text = ''
          fetchMessageBoards()
        } else {
          ElMessage.error(res.msg || '提交问题失败')
        }
      } catch (error) {
        console.error('提交问题失败:', error)
        ElMessage.error('提交问题失败')
      }
    }
  })
}

// 查看问题详情
const viewDetail = (issueId: number) => {
  router.push(`/message-board/${issueId}`)
}

onMounted(() => {
  fetchMessageBoards()
})
</script>

<style scoped>
.message-board-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.page-header {
  text-align: center;
  margin: 64px auto 20px;
  max-width: 1200px;
  padding: 0 20px;
}

.page-header h2 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 32px;
}

.subtitle {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

.action-bar {
  max-width: 1200px;
  margin: 0 auto 20px;
  padding: 0 20px;
}

.message-board-list {
  width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
  flex: 1;
}

.card-container {
  width: 70%;
  margin: 0 auto;
  min-width: 600px;
}

.message-board-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.message-board-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.card-main {
  padding: 30px;
  display: flex;
  flex-direction: column;
  min-height: 200px;
}

.message-board-content {
  color: #606266;
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 16px;
  flex: 1;
  overflow: hidden;
}

.content-text {
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}

.content-text::-webkit-scrollbar {
  width: 6px;
}

.content-text::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.content-text::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.message-board-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  margin-top: auto;
}

.message-board-meta {
  display: flex;
  gap: 16px;
}

.author {
  color: #409EFF;
  font-weight: 500;
}

.time {
  color: #909399;
}

.dialog-footer {
  margin-top: 20px;
}
</style> 